<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/gmxs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/gmxs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/gmxs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/gmxs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/gmxs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/gmxs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/gmxs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java," />





  <link rel="alternate" href="/gmxs/atom.xml" title="葛木小舍先生的博客" type="application/atom+xml" />






<meta name="description" content="接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面,之后两个系列将结合一起,缩短篇幅,精要内容.">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="java字符串">
<meta property="og:url" content="http://yoursite.com/2019/04/04/java初探/java字符串/index.html">
<meta property="og:site_name" content="葛木小舍先生的博客">
<meta property="og:description" content="接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面,之后两个系列将结合一起,缩短篇幅,精要内容.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-df12de59a55804be.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-04-14T07:21:57.626Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java字符串">
<meta name="twitter:description" content="接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面,之后两个系列将结合一起,缩短篇幅,精要内容.">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/8067684-df12de59a55804be.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/gmxs/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/04/java初探/java字符串/"/>





  <title>java字符串 | 葛木小舍先生的博客</title>
  









  
  <script type="text/javascript"
  color="0,0,255" opacity='0.7' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>


	<a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/gmxs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">葛木小舍先生的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/gmxs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/gmxs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/gmxs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/gmxs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/gmxs/2019/04/04/java初探/java字符串/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="葛木小舍先生">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/gmxs/images/touxiang.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="葛木小舍先生的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java字符串</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-04T00:00:00+08:00">
                2019-04-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/gmxs/categories/Java初探/" itemprop="url" rel="index">
                    <span itemprop="name">Java初探</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/gmxs/2019/04/04/java初探/java字符串/" class="leancloud_visitors" data-flag-title="java字符串">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
			 <span>℃</span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,331
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          
              <div class="post-description">
                  接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面,之后两个系列将结合一起,缩短篇幅,精要内容.
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li>前言<br>接下来将暂时将重心偏移向实际操作,不在将大量时间花费在详细的知识点整理上,将会简略知识总结笔记的记录,加强实际练习的时间,实例练习篇也不再同步进行,我会将部分我觉得重要的源码更新在每节知识点后面,之后两个系列将结合一起,缩短篇幅,精要内容.</li>
</ul>
<hr>
<blockquote>
<p>字符串时Java语言中经常处理的对像,我们会在各种地方遇到对字符串的处理.在java语言中字符串是作为String类的实例来处理的,是以对象的方式处理字符串. </p>
</blockquote>
<ul>
<li>关于类,及类的实例化对象.<br>在前面的学习中我们了解到,在Java中,最基本的构造机制之一就是类,类中可以构造各种方法.而Java就是基于这条件下,通过各种定义好的类,方法.集合成标准类库,以提供给我们使用,类和对象的思想也来自与现实社会结构,自然科学.在分类科学中,统计学等,都有应用,将世界的各种事物,有同种特性的归为一类,比如鸟类,而当面前有一只鸟,它正好属于这个鸟类,那么这只鸟就是鸟类实例化的一个对象,Java语言,就是使用这种思想架构的.关于类及类的对象,在后面再进行深入学习.</li>
</ul>
<hr>
<p>涉及到的知识点:</p>
<ul>
<li>字符串的创建 </li>
<li>连接字符串</li>
<li>获取字符串信息</li>
<li>字符串操作</li>
<li>格式化字符串</li>
</ul>
<p>这里关于字符串的格式化,我另写了一个外篇专门来归纳总结了一下.</p>
<p><a href="https://www.jianshu.com/p/5192a769e0ea" target="_blank" rel="noopener">格式化字符串</a></p>
<hr>
<ul>
<li>字符串的声明创建<br>我们知道了字符串的创建,就是使用String类的构造方法.<br>那么我们看一下String类中的Structure(结构体),并找到一系列的String()构造函数.</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-df12de59a55804be.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="2019-4-3-08.png"></p>
<p>这下我们知道了,String的构造方法是有多少,除了最简单的String()方法,还提供了各种通过不同数据类的数组构建String对象的方法.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public void sty_createString()&#123;</span><br><span class="line">       String astr= &quot;hello&quot;; // 引用字符串常量创建一个字符串变量.</span><br><span class="line">       char a[] = &#123;&apos;a&apos;,&apos;b&apos;,&apos;c&apos;&#125;;  // 字符数组</span><br><span class="line">       byte b[] = &#123;2,54,23,12&#125;;  // byte型数组</span><br><span class="line">       /**</span><br><span class="line">        * String(char[])构造方法,将字符数组所有的值连接起来创建一个字符串对象.</span><br><span class="line">        * */</span><br><span class="line">       String s=new String(a);</span><br><span class="line"></span><br><span class="line">       /**</span><br><span class="line">        *  String(char[],int offset,int length)方法</span><br><span class="line">        *  抽取字符数组中的一段字符创建字符串对象.offset 表示开始截取的位置.</span><br><span class="line">        */</span><br><span class="line">       String astr3 = new String(a,1,2);</span><br><span class="line">       String astr4 = new String(b);</span><br><span class="line">       String astr5 = new String(b,3,2);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>其中两个int型参数,分别定义了截取数组的开始位置和截取长度.</p>
<hr>
<ul>
<li><p>字符串的连接<br>字符串的连接十分简单,在Java语言中,直接使用+就可以连接两个不同的字符串,或者将一个字符串与其他类型的变量连接,其输出结果将调用String类的toString方法,将格式转换为字符串输出. </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">String str1,str2;</span><br><span class="line">int a=45;</span><br><span class="line">str1=&quot;dfgg&quot;+&quot;adf&quot;;</span><br><span class="line">str2=&quot;asd&quot;;</span><br><span class="line">String str3 = str1+str2;</span><br><span class="line">System.ou.println(&quot;字符连接&quot;+a);</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>获取字符串信息</strong></p>
</li>
<li><p>获取字符串长度:String()类的length()方法可以获取字符串长度.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// 获取字符串长度.length()方法</span><br><span class="line">        System.out.println(&quot;主字符串的长度是&quot;+mstr.length());</span><br></pre></td></tr></table></figure>
</li>
<li><p>字符串查找:<br>String类中的indexOf()与lastindexOf()方法都可以搜索字符串中的指定条件的字符和字符串.<br>indexOf()方法,返回字符第一次出现的位置,lastindexOf()方法返回字符最后一次出现的位置.当他们没有检索到字符串时,将返回-1.</p>
</li>
</ul>
<p>两个方法的参数都为检索字符串.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// 检索字符串 ,indexOf()方法,lastIndex()方法</span><br><span class="line">        int fint = mstr.indexOf(Instr); // 调用检索字符串参数instr.</span><br><span class="line">        int lint = mstr.lastIndexOf(Instr);</span><br><span class="line">        System.out.println(Instr+&quot;字符(串)首次出现的位置是:&quot;+fint);</span><br><span class="line">        System.out.println(Instr+&quot;字符(串)最后出现的位置是:&quot;+lint);</span><br></pre></td></tr></table></figure></p>
<ul>
<li><p>获取指定位置的字符<br>String类下的charAt()方法,其参数为int型,表示指定位置的下标,通过下表找到相对应的字符.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//获取指定位置的字符,charAt()方法</span><br><span class="line">      char setchar = mstr.charAt(aint);</span><br><span class="line">      System.out.println(aint+&quot;位置的字符是:&quot;+setchar);</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>字符串操作</strong></p>
</li>
<li><p>获取子字符串<br>substring()方法,按下标截取字符串,重载有两种方法,表示两种不同的截取方式.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String cstr = mstr.substring(3); // substring(int beginindex),传一个int型参数,表示从参数开始截取到结尾.</span><br><span class="line">      String cstr2 = mstr.substring(3,6); // substring(int beginindex,int endindex)两个参数,表示截取两个参数之间的字符串.</span><br><span class="line">      System.out.println(&quot;从第3开始获取子字符串&quot;+cstr);</span><br><span class="line">      System.out.println(&quot;截取3到6字符串&quot;+cstr2);</span><br></pre></td></tr></table></figure>
</li>
<li><p>去除首尾空格<br>trim()方法为我们提供了去除首位空格的方法,这个方法应当是用在储存信息时去除首尾无意义的多余空格,减少空间占用.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//去除空格,trim()方法可以直接返回字符串的副本,忽略前导和尾部空格.通常用于储存信息时,去除首尾无意义的空格.</span><br><span class="line">      String vstr = mstr.trim();</span><br><span class="line">      System.out.println(&quot;去除首位空格的字符串副本:&quot;+vstr);</span><br></pre></td></tr></table></figure>
</li>
<li><p>字符串替换<br>replace()方法给我们提供了字符(转换)的方法,可以将一个新的字符(串)替换掉一个就的字符串,这在一般的文本编辑中时常用到.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">//字符串替换,replace()方法可以实现将指定字符或字符串替换成新的字符串.replace(char oldchar,char newchar)</span><br><span class="line">      String nstr= mstr.replace(&apos;a&apos;,&apos;b&apos;);</span><br><span class="line">      String nstr2 = mstr.replace(&quot;str&quot;,&quot;asr&quot;);</span><br><span class="line">      System.out.println(&quot;替换后的字符串&quot;+nstr);</span><br><span class="line">      System.out.println(&quot;替换后的字符串&quot;+nstr2);</span><br></pre></td></tr></table></figure>
</li>
<li><p>比较两个字符串是否相等<br>equals()方法给我们提供了比较两个字符串是否相同的方法,我们知道,两个字符串的比较不能单纯的使用==,这是因为比较运算符比较的是两个字符串的地址是否相同,即使两者的内容相同,两者的内存地址也是不同的,使用比较运算符无法比较两个字符串之间的关系.<br>所以需要使用到equals方法.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//判断字符串是否相等,equals()方法用于比较两个字符串是否相等.</span><br><span class="line">       System.out.println(&quot;字符串是否和abc相等:&quot;+mstr.equals(&quot;abc&quot;));</span><br></pre></td></tr></table></figure>
</li>
<li><p>判断字符串的开始和结尾<br>startsWith(),endsWith()方法可以判断字符串是否按照参数开始或结尾,这常用与字符串的校验.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//判断字符串的开始结尾 startsWith(),endsWith()方法分别判断字符串是否以指定的形式结束.返回值为布尔类型.</span><br><span class="line">        System.out.println(&quot;字符串是否以a开始:&quot;+mstr.startsWith(&quot;a&quot;));</span><br><span class="line">        System.out.println(&quot;字符串是否以.结束:&quot;+mstr.endsWith(&quot;.&quot;));</span><br></pre></td></tr></table></figure>
</li>
<li><p>按字典顺序比较两个字符串<br>compareTo()方法为按字典排序比较两个字符串,比较是其unicode值.将两个String对象表示的字符序列与参数字符串所表示的字符串序列进行比较.按字符序列,如果String对象在参数字符序列的前面,返回一个负值,在后面返回一个正值,如果相等,则返回0.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.out.println(&quot;与字符串hyz按字典排序相比较&quot;+mstr.compareTo(&quot;hyz&quot;));</span><br></pre></td></tr></table></figure>
</li>
<li><p>字符串大小写转换<br>toLowerCase(),toUpperCase()方法.前者将字符串所有字符大写改为小写,后者从小写改为大写.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">System.out.println(&quot;字符串全转为小写:&quot;+mstr.toLowerCase());</span><br><span class="line">        System.out.println(&quot;字符串全转为大写:&quot;+mstr.toUpperCase());</span><br></pre></td></tr></table></figure>
</li>
<li><p>字符串分割<br>split()方法,重载有两种不同的分割方式,split(String regex)参数为指定的分割符,,split(String regex,int limit),后一个参数是指定分割次数,从前往后.字符串分割会将字符串储存在一个字符串数组里.打印需要遍历它.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">String[] regexmstr = mstr.split(&quot;e&quot;);</span><br><span class="line">       String[] regexmstr2 = mstr.split(&quot;e&quot;,3);</span><br><span class="line">       for (String a: regexmstr)&#123;  // 对字符串数组遍历打印.</span><br><span class="line">           System.out.print(&quot;[&quot;+a+&quot;]&quot;);</span><br><span class="line">       &#125;</span><br><span class="line">       System.out.println(); // 换行</span><br><span class="line">       for (String a:regexmstr2)&#123;</span><br><span class="line">           System.out.print(&quot;[&quot;+a+&quot;]&quot;);</span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<hr>
<ul>
<li>源代码<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br></pre></td><td class="code"><pre><span class="line">package day_4_3;</span><br><span class="line">import java.util.Scanner;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * @outhor xiaoshe</span><br><span class="line"> * @date 2019/4/3  - @time 18:29</span><br><span class="line"> * 字符串的学习</span><br><span class="line"> */</span><br><span class="line">public class Sty_String &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        Sty_String styString = new Sty_String();</span><br><span class="line">        styString.sty_createString();</span><br><span class="line"></span><br><span class="line">        Scanner scanner = new Scanner(System.in);</span><br><span class="line">        System.out.println(&quot;输入主字符串:&quot;);</span><br><span class="line">        String mstr = scanner.nextLine();</span><br><span class="line">        System.out.println(&quot;输入需要查询的字符(或字符串):&quot;);</span><br><span class="line">        String instr = scanner.next();</span><br><span class="line">        System.out.println(&quot;输入指定字符的位置:&quot;);</span><br><span class="line">        int aint = scanner.nextInt();</span><br><span class="line">        styString.Sty_getStringInfo(mstr,instr,aint);</span><br><span class="line">        styString.sty_setString(mstr);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * String类中的两种构造字符串的方法.</span><br><span class="line">     */</span><br><span class="line">    public void sty_createString()&#123;</span><br><span class="line">        String astr= &quot;hello&quot;; // 引用字符串常量创建一个字符串变量.</span><br><span class="line">        char a[] = &#123;&apos;a&apos;,&apos;b&apos;,&apos;c&apos;&#125;;  // 字符数组</span><br><span class="line">        byte b[] = &#123;2,54,23,12&#125;;  // byte型数组</span><br><span class="line">        /**</span><br><span class="line">         * String(char[])构造方法,将字符数组所有的值连接起来创建一个字符串对象.</span><br><span class="line">         * */</span><br><span class="line">        String s=new String(a);</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         *  String(char a[],int offset,int length)方法</span><br><span class="line">         *  抽取字符数组中的一段字符创建字符串对象.offset 开始截取的位置.</span><br><span class="line">         */</span><br><span class="line">        String astr3 = new String(a,0,2);</span><br><span class="line">        String astr4 = new String(b);</span><br><span class="line">        String astr5 = new String(b,0,2);</span><br><span class="line">        System.out.println(astr+&quot;\n&quot;+astr3+&quot;\n&quot;+astr4+&quot;\n&quot;+astr5);</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 获取字符串信息</span><br><span class="line">     */</span><br><span class="line">    public void Sty_getStringInfo(String mstr ,String Instr,int aint)&#123;</span><br><span class="line"></span><br><span class="line">        // 获取字符串长度.length()方法</span><br><span class="line">        System.out.println(&quot;主字符串的长度是&quot;+mstr.length());</span><br><span class="line">        // 检索字符串 ,indexOf()方法,lastIndex()方法</span><br><span class="line">        int fint = mstr.indexOf(Instr);</span><br><span class="line">        int lint = mstr.lastIndexOf(Instr);</span><br><span class="line">        System.out.println(Instr+&quot;字符(串)首次出现的位置是:&quot;+fint);</span><br><span class="line">        System.out.println(Instr+&quot;字符(串)最后出现的位置是:&quot;+lint);</span><br><span class="line">        //获取指定位置的字符,charAt()方法</span><br><span class="line">        char setchar = mstr.charAt(aint);</span><br><span class="line">        System.out.println(aint+&quot;位置的字符是:&quot;+setchar);</span><br><span class="line">    &#125;</span><br><span class="line">    /**</span><br><span class="line">     * 字符串操作</span><br><span class="line">     */</span><br><span class="line">    public void sty_setString(String mstr)&#123;</span><br><span class="line">        /**</span><br><span class="line">         * 获取子字符串 substring()方法,按下标值截取子字符串,下标是由0开始的.</span><br><span class="line">         * substring()方法有两种不同的重载方法,分别代表两种不同的截取方式.</span><br><span class="line">         */</span><br><span class="line"></span><br><span class="line">        String cstr = mstr.substring(3); // substring(int beginindex),传一个int型参数,表示从参数开始截取到结尾.</span><br><span class="line">        String cstr2 = mstr.substring(3,6); // substring(int beginindex,int endindex)两个参数,表示截取两个参数之间的字符串.</span><br><span class="line">        System.out.println(&quot;从第3开始获取子字符串&quot;+cstr);</span><br><span class="line">        System.out.println(&quot;截取3到6字符串&quot;+cstr2);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        //去除空格,trim()方法可以直接返回字符串的副本,忽略前导和尾部空格.通常用于储存信息时,去除首尾无意义的空格.</span><br><span class="line">        String vstr = mstr.trim();</span><br><span class="line">        System.out.println(&quot;去除首位空格的字符串副本:&quot;+vstr);</span><br><span class="line"></span><br><span class="line">        //字符串替换,replace()方法可以实现将指定字符或字符串替换成新的字符串.replace(char oldchar,char newchar)</span><br><span class="line">        String nstr= mstr.replace(&apos;a&apos;,&apos;b&apos;);</span><br><span class="line">        String nstr2 = mstr.replace(&quot;str&quot;,&quot;asr&quot;);</span><br><span class="line">        System.out.println(&quot;替换后的字符串&quot;+nstr);</span><br><span class="line">        System.out.println(&quot;替换后的字符串&quot;+nstr2);</span><br><span class="line"></span><br><span class="line">        //判断字符串是否相等,equals()方法用于比较两个字符串是否相等.</span><br><span class="line">        System.out.println(&quot;字符串是否和abc相等:&quot;+mstr.equals(&quot;abc&quot;));</span><br><span class="line"></span><br><span class="line">        //判断字符串的开始结尾 startsWith(),endsWith()方法分别判断字符串是否以指定的形式结束.返回值为布尔类型.</span><br><span class="line">        System.out.println(&quot;字符串是否以a开始:&quot;+mstr.startsWith(&quot;a&quot;));</span><br><span class="line">        System.out.println(&quot;字符串是否以.结束:&quot;+mstr.endsWith(&quot;.&quot;));</span><br><span class="line"></span><br><span class="line">        /**</span><br><span class="line">         * 按字典顺序比较两个字符串,compareTo()方法为按字典排序比较两个字符串,比较是其unicode值.</span><br><span class="line">         * 将两个String对象表示的字符序列与参数字符串所表示的字符串序列进行比较.</span><br><span class="line">         * 按字符序列,如果String对象在参数字符序列的前面,返回一个负值,在后面返回一个正值,如果相等,则返回0</span><br><span class="line">         */</span><br><span class="line">        System.out.println(&quot;与字符串hyz按字典排序相比较&quot;+mstr.compareTo(&quot;hyz&quot;));</span><br><span class="line"></span><br><span class="line">        //字母大小写转换,toLowerCase(),toUpperCase()方法.前者将字符串所有字符大写改为小写,后者从小写改为大写.</span><br><span class="line">        System.out.println(&quot;字符串全转为小写:&quot;+mstr.toLowerCase());</span><br><span class="line">        System.out.println(&quot;字符串全转为大写:&quot;+mstr.toUpperCase());</span><br><span class="line"></span><br><span class="line">        //字符串分割split()方法,重载有两种不同的分割方式,split(String regex)参数为指定的分割符,</span><br><span class="line">        String[] regexmstr = mstr.split(&quot;e&quot;);</span><br><span class="line">        String[] regexmstr2 = mstr.split(&quot;e&quot;,3);</span><br><span class="line">        for (String a: regexmstr)&#123;  // 对字符串数组遍历打印.</span><br><span class="line">            System.out.print(&quot;[&quot;+a+&quot;]&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(); // 换行</span><br><span class="line">        for (String a:regexmstr2)&#123;</span><br><span class="line">            System.out.print(&quot;[&quot;+a+&quot;]&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<hr>
<p>关于String类,就先学习到这些基础和常用的方法了.关于String类的其他众多的方法,我们可以直接查看String类通过structure(结构体)视窗,进行了解.</p>
<hr>
<p>完<br>更新时间:<br>2019-4-4<br>1:31</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你现在可以打赏本宝宝啦！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weixing.png" alt="葛木小舍先生 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/zhifubao.png" alt="葛木小舍先生 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/gmxs/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/gmxs/2019/04/02/java初探/流程控制语句/" rel="next" title="java流程控制语句">
                <i class="fa fa-chevron-left"></i> java流程控制语句
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/gmxs/2019/04/05/java初探/数组/" rel="prev" title="Java数组">
                Java数组 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTg1Ni8xMjM5Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/gmxs/images/touxiang.png"
                alt="葛木小舍先生" />
            
              <p class="site-author-name" itemprop="name">葛木小舍先生</p>
              <p class="site-description motion-element" itemprop="description">不管过去过的如何，现在活的如何，将来将会如何。努力做好自己，朝梦想中的自己努力前进。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/gmxs/archives/">
              
                  <span class="site-state-item-count">61</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/gmxs/categories/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/gmxs/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/gmxs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/gemuxiaoshe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MaYaPeng2017@outlook.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5967971229/home?wvr=5&sudaref=graph.qq.com" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                个人收集站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gemumiaoshe.wordpress.com/" title="葛木小舍先生的小世界" target="_blank">葛木小舍先生的小世界</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.w3cschool.cn/html/" title="W3Cschool" target="_blank">W3Cschool</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="web前端导航" target="_blank">web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.itcast.cn/" title="传智播客" target="_blank">传智播客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://5sing.kugou.com/index.html" title="5sing" target="_blank">5sing</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.mikecrm.com/login.php?s=2&d=form.php#/list/" title="麦客CRM" target="_blank">麦客CRM</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.51cto.com/" title="51CTO" target="_blank">51CTO</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">葛木小舍先生</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共111.1k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/gmxs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/gmxs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/gmxs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/gmxs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/gmxs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/gmxs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/gmxs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
